package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.service.GoodsService;
import com.dongdongshop.util.JwtUtil;
import com.dongdongshop.util.LoginUser;
import com.dongdongshop.vo.GoodsVO;
import com.dongdongshop.vo.ItemVO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("addGoods")
    public Result addGoods(@RequestHeader("AutharizeToken") String AutharizeToken,@RequestBody GoodsVO goodsVO){
        Claims claims = jwtUtil.parseJwt(AutharizeToken);
        LoginUser loginUser = JSONObject.parseObject(claims.getSubject(), LoginUser.class);
        int i = goodsService.addGoods(goodsVO,loginUser);
        if(i >= 1){
            return Result.OK();
        }
        return Result.RESPOSE(ResultEnum.ERROR);
    }

    @GetMapping("getAllGoods")
    public Result getAllGoods(){
        List<GoodsVO> list = goodsService.getAllGoods();
        return Result.OK().setData(list);
    }

    @PostMapping("changeStatus")
    public Result changeStatus(@RequestBody List<Long> ids){
        int  i = goodsService.changeStatus(ids);
        if(i >= 1){
            return Result.OK();
        }
        return Result.FAIL();
    }

    @PostMapping("getGoodsById")
    public Result getGoodsById(@RequestParam Long goodsId){
        GoodsVO goodsVO = goodsService.getGoodsById(goodsId);
        return Result.OK().setData(goodsVO);
    }

    @GetMapping("getItemById")
    public Result getItemById(@RequestParam Long itemId){
        ItemVO itemVO = goodsService.getItemById(itemId);
        /*int x = 9 / 0;*/
        return Result.OK().setData(itemVO);
    }

}
